package me.jiatao.taobaotools.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import me.jiatao.taobaotools.R;
import me.jiatao.taobaotools.model.EvaluateCountItem;
import me.jiatao.taobaotools.utils.ShowMessageUtils;
import me.jiatao.taobaotools.view.X5WebView;

public class LoginActivity extends BaseActivity {
    private X5WebView loginWebView;
    private EvaluateCountItem evaluateCountItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        evaluateCountItem = new EvaluateCountItem();
        evaluateCountItem.setWeek(2);
        evaluateCountItem.setWeek(7);
        evaluateCountItem.setSixMonth(20);

        loginWebView = (X5WebView) findViewById(R.id.loginWebView);
        initWebView();
    }

    private void initWebView() {
        WebSettings webSetting = loginWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);

        //扩大比例的缩放
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setLoadWithOverviewMode(true);

//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setAppCacheEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setDomStorageEnabled(true);
        //webSetting.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        loginWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        loginWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.contains("//rate.taobao.com")) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String CookieStr = cookieManager.getCookie(url);
                    synCookies(activity, "taobao.com", CookieStr);

                    ShowMessageUtils.show(activity, "登录成功");
                    finish();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

        loginWebView.loadUrl("https://login.m.taobao.com/login.htm?redirectURL=http%3A%2F%2Frate.taobao.com%2Fuser-myrate-UvFcYMFQWOFN4--buyerOrSeller%257C3--receivedOrPosted%257C1.htm%3Fuser_id%3DUvFcYMFQWOFN4%26buyerOrSeller%3D3%26receivedOrPosted%3D1&loginFrom=wap_tb");
    }

    /**
     * 获取本地存储的 Cookie 集合
     *
     * @return Cookie 键值对
     */
    public Map<String, String> getCookieMap(String cookie) {
        Map<String, String> cookieMap = new HashMap<>();
        if (!TextUtils.isEmpty(cookie)) {
            String[] cookieArray = cookie.split(";");// 多个Cookie是使用分号分隔的
            for (int i = 0; i < cookieArray.length; i++) {
                int position = cookieArray[i].indexOf("=");// 在Cookie中键值使用等号分隔
                String cookieName = cookieArray[i].substring(0, position);// 获取键
                String cookieValue = cookieArray[i].substring(position + 1);// 获取值
                cookieMap.put(cookieName, URLEncoder.encode(cookieValue));// 存至Map
                // 解码使用 URLEncoder.encode(str, "UTF-8");
            }
        }
        return cookieMap;
    }


    /**
     * 设置Cookie
     *
     * @param context
     * @param url
     * @param cookie  格式：uid=21233 如需设置多个，需要多次调用
     */
    public void synCookies(Context context, String url, String cookie) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);

        Map<String, String> cookieMap = getCookieMap(cookie);// 获取键值对
        for (Map.Entry<String, String> entry : cookieMap.entrySet()) {// 遍历 Map
            String value = entry.getKey() + "=" + entry.getValue();// 键值对拼接成 value
            cookieManager.setCookie(url, value);// 设置 Cookie
        }
        CookieSyncManager.getInstance().sync();
    }
}
